package app.server.project.main.service.service.cms;

import app.server.project.core.http.CMSLstResp;
import app.server.project.core.util.GlobalValChangeEvent;
import app.server.project.main.service.db.dao.cfg.GlobalCfgDao;
import app.server.project.main.service.db.entity.cfg.GlobalCfgEntity;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Data
@AllArgsConstructor
@Service
public class GlobalCfgService {

    private GlobalCfgDao globalCfgDao;
    private ApplicationEventPublisher applicationEventPublisher;
    private GMService gmService;

    /**
     * 读取全部全局配置
     *
     * @return
     */
    public CMSLstResp getAllGlobalCfg() {
        var lst = this.globalCfgDao.getGlobalCfgEntityList();
        return CMSLstResp.of(lst, lst.size());
    }

    public void save(GlobalCfgEntity globalCfgEntity) {
        if (StrUtil.isBlank(globalCfgEntity.getId())) return;
        this.globalCfgDao.removeById(globalCfgEntity.getId());
        this.globalCfgDao.save(globalCfgEntity);
        this.globalCfgDao.init();
        //环境变更
        this.applicationEventPublisher.publishEvent(GlobalValChangeEvent.of());
    }

    public void del(GlobalCfgEntity globalCfgEntity) {
        if (StrUtil.isBlank(globalCfgEntity.getId())) return;
        this.globalCfgDao.removeById(globalCfgEntity.getId());
        this.globalCfgDao.init();
    }

    public void uploadSingleImg(MultipartFile files, String gId) {
        var imgUrl = this.gmService.uploadSingleImg(files);
        GlobalCfgEntity data;
        data = this.globalCfgDao.getOneByKey(gId);
        data.setVal(imgUrl);
        this.globalCfgDao.saveOrUpdate(data);
        this.globalCfgDao.init();
    }
}
